Final & This

In Scala, the ‘this’ keyword lets us refer to the current object. ‘final’ prevents a class from deriving members from its superclass. These can be variables, methods, and classes. When we want to refer to the current object for a class, we use the ‘this’ keyword. Then using the dot operator (.), we can refer to instance variables, methods and constructors by using this keyword. This keyword is also used with auxiliary constructor.   
Scala This
class myClass{
var id:Int = 0
var name: String = ""
def this(id:Int, name:String){
this()
this.id = id
this.name = name
}
def show(){
println(id+" "+name)
}
}

object test{
def main(args:Array[String]){
var t = new myClass(101,"Martin")
t.show()
}
}
Scala Final
When we don’t want a class to be able to inherit a member from its superclass, we declare that member final. This member may be a variable, a method, or even a class.
class Vehicle{
val speed:Int = 60
}
class Bike extends Vehicle{
override val speed:Int = 100
def show(){
println(speed)
}
}

object MainObject{
def main(args:Array[String]){
var b = new Bike()
b.show()
}
}
Extending final members
class Vehicle{
final val speed:Int = 60
}
class Bike extends Vehicle{
override val speed:Int = 100
def show(){
println(speed)
}
}
object test{
def main(args:Array[String]){
var b = new Bike()
b.show()
}
}
 cannot override final member:
final val speed: Int (defined in class Vehicle)
override val speed:Int = 100

No comments:

Post a Comment